package com.config;

import com.json.JacksonObjectMapper;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.interceptor.AuthorizationInterceptor;


import java.util.List;

@Configuration
@Slf4j
public class InterceptorConfig extends WebMvcConfigurationSupport{

	@Bean
    public AuthorizationInterceptor getAuthorizationInterceptor() {
        return new AuthorizationInterceptor();
    }

	@Override
    public void addInterceptors(InterceptorRegistry registry) {
		log.info("开始注册自定义拦截器...");
        registry.addInterceptor(getAuthorizationInterceptor())
				.addPathPatterns("/**")
				.excludePathPatterns("/static/**");
        super.addInterceptors(registry);
	}

	/**
	 * springboot 2.0配置WebMvcConfigurationSupport之后，会导致默认配置被覆盖，要访问静态资源需要重写addResourceHandlers方法
	 */
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

		registry.addResourceHandler("/**")
        		.addResourceLocations("classpath:/resources/")
        		.addResourceLocations("classpath:/static/")
        		.addResourceLocations("classpath:/admin/")
        		.addResourceLocations("classpath:/img/")
        		.addResourceLocations("classpath:/front/")
        		.addResourceLocations("classpath:/public/");
		super.addResourceHandlers(registry);
    }




	/**
	 * 扩展spring mvc框架的消息转换器
	 * @param converters
	 */
	@Override
	protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		log.info("扩展消息转换器");
		//创建一个消息转换器对象
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		//要为消息转换器没置一个对象转换器,对象转换器可以将java对象序列化为json数组
		converter.setObjectMapper(new JacksonObjectMapper());
		//将自己的消息转换器加入容器中
		converters.add(0,converter);

		super.extendMessageConverters(converters);
	}
}
